<template>
  <div class="goods_page" :class="{ box_fixed: isFixed }">
    <template v-if="!isNoData">
      <template v-if="mainData">
        <div class="gp_header">
          <div class="gp_updata_date">
            <p>数据更新时间：{{ updataDate }}</p>
            <i class="updata_btn" @click="updataFn"></i>
          </div>
          <div class="gp_info" :class="{ fixed: isFixed }" ref="headerBox">
            <div class="img_box">
              <img
                :src="mainData.proLogo"
                v-errorImg:goods
                @click="ImgPreview(mainData.proLogo)"
              />
            </div>
            <div class="text_box">
              <h2 class="goods_icon">
                <span>{{ mainData.proTitle }}</span>
              </h2>
              <div class="price_box">
                <div class="price_text">
                  <p>
                    <i>￥</i>
                    <span class="price">{{ mainData.proPrice }}</span>
                    佣金率 {{ mainData.commissionRate | rate }}
                  </p>
                  <p v-if="mainData.maxPrice || mainData.livePrice">
                    直播价
                    {{ [mainData.maxPrice, mainData.livePrice] | setPrice }}
                  </p>
                </div>
                <div class="collect_btn" :class="{ active: isCollect }" @click="collectFn">
                  <i></i>
                  <span>{{ isCollect ? "已收藏" : "收藏" }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="gp_data">
          <h3 class="title_h3">
            <span>数据概览</span>
          </h3>
          <template v-if="!loading">
            <template v-if="hasRoot">
              <div class="data_box" v-if="totalData">
                <div class="data_item">
                  <!-- <p class="strong">{{ format_num(totalData.volume) }}</p> -->
                  <p class="strong" v-if="totalData.liveVolume || totalData.awemeVolume">
                    {{ format_num(totalData.liveVolume + totalData.awemeVolume) }}
                  </p>
                  <p class="strong" v-if="totalData.liveVolume == 0 && totalData.awemeVolume == 0">
                    {{ format_num(totalData.liveVolume + totalData.awemeVolume) }}
                  </p>
                  <p>30天总销量</p>
                </div>
                <div class="data_item">
                  <p class="strong">{{ format_num(totalData.liveVolume) }}</p>
                  <p>30天直播销量</p>
                </div>
                <div class="data_item">
                  <p class="strong">{{ format_num(totalData.awemeVolume)}}</p>
                  <p>30天视频销量</p>
                </div>
                <div class="data_item">
                  <p class="strong">{{ format_num(totalData.associatedlive) }}</p>
                  <p>30天关联直播</p>
                </div>
                <div class="data_item">
                  <p class="strong">{{ format_num(totalData.associatedVideo) }}</p>
                  <p>30天带货视频</p>
                </div>
                <div class="data_item">
                  <p class="strong">{{ format_num(totalData.associatedAuthor) }}</p>
                  <p>30天关联达人</p>
                </div>
              </div>
            </template>
            <noPower height="3.7rem" :minLeve="$store.state.userRoot[8][131].ownerMinLevel" v-else />
          </template>
          <div class="loading_box" v-else>
            <van-loading class="loading" type="spinner" :vertical="true" />
          </div>
        </div>
        <div class="goods_main">
          <van-tabs
            v-model="active"
            :offset-top="'2.29rem'"
            :sticky="true"
            @scroll="tabScrollFn"
            scrollspy
            :duration="0.1"
          >
            <van-tab title="直播详情">
              <liveDetails class="model_interval" />
            </van-tab>
            <van-tab title="视频详情">
              <videoDetails class="model_interval" />
            </van-tab>
            <van-tab title="达人详情">
              <talentDetails class="model_interval" />
            </van-tab>
            <van-tab title="观众分析">
              <audienceDetails class="model_interval" />
            </van-tab>
          </van-tabs>
          <!-- 我是有底线的~ -->
          <FooterText />
        </div>
      </template>
    </template>
    <div class="nodata_page" v-else>
      <div class="img_box">
        <img src="@/assets/three/noData.png" alt />
      </div>
      <p>暂无数据</p>
    </div>
    <PageLoading v-if="isLoading" />
  </div>
</template>

<script>
import { ImagePreview } from 'vant';
import liveDetails from './goodsDetails/goodsLiveDetails.vue'; //直播详情
import videoDetails from './goodsDetails/goodsVideoDetails.vue'; //视频详情
import talentDetails from './goodsDetails/goodsTalentDetails.vue'; //达人详情
import audienceDetails from './goodsDetails/goodsAudienceDetails.vue'; //观众画像分析
import PageLoading from '@/component/pageLoading.vue';
import errorImg from '@/assets/img/shop.png'; //图片

export default {
  props: {},
  data() {
    return {
      updataDate: '',
      proId: this.$route.query.id,
      mainData: '', //商品详情数据
      totalData: '', //数据概览数据
      isCollect: 0, //是否收藏
      active: 0, //tab切换下标
      tabIsfixed: false, //  tab是否吸顶
      isFixed: false,
      fixedVal: 0,
      isFristScroll: false, //是否出发过一次吸顶
      isNoData: false, //是否无数据
      loading: true,
      hasRoot: true,
      isLoading: true,
      errorImg: errorImg
    };
  },
  components: {
    liveDetails,
    videoDetails,
    talentDetails,
    audienceDetails,
    PageLoading
  },
  activated() {
    if (!this.$route.meta.keepAlive) {
      this.getMainData();
      this.getTotalData();
    }
    // 恢复成默认的false，避免isBack一直是true，导致下次无法获取数据
  },
  created() {
    this.getMainData();
    this.getTotalData();
  },
  mounted() {
    window.onscroll = e => {
      this.setHeaderFixed();
    };
  },
  methods: {
    updataFn() {
      //更新
      this.loading = true;
      this.getMainData();
      this.getTotalData();
    },
    tabScrollFn(callbackPms) {
      //获取tab置顶的参数
      // console.log(callbackPms)
      this.tabIsfixed = callbackPms.isFixed;
    },
    setHeaderFixed() {
      //设置顶部浮动方法
      let headerBoxEl = this.$refs.headerBox;
      if (!headerBoxEl) return;
      if (!this.isFristScroll) {
        let elTop = headerBoxEl.offsetTop;
        this.fixedVal = elTop;
        this.isFristScroll = true;
      }
      let elHeight = headerBoxEl.offsetHeight;
      let windowHeight = window.screen.height;
      let documentHeight = document.body.offsetHeight || document.body.clientHeight;
      let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
      if (scrollTop >= this.fixedVal && documentHeight > windowHeight + elHeight) {
        this.isFixed = true;
      } else {
        this.isFixed = false;
      }
    },
    getMainData() {
      //获取商品详情数据
      return new Promise((resolve, reject) => {
        this.$axios({
          method: 'get',
          url: '/api/product/newinfo',
          params: {
            // proId: "3487748950235198351"
            proId: this.proId
          }
        }).then(res => {
          this.isLoading = false;
          resolve(res);
          if (res.data.code == 0) {
            this.mainData = res.data.data;
            this.updataDate = this.timestamp(this.mainData.timeUnix, 'Y-M-D h:m:s');
            this.isCollect = res.data.data.isCollect;
          }
        });
      });
    },
    collectFn() {
      let that = this;
      //收藏接口
      let url = '';
      if (this.isCollect) {
        url = '/api/collection/CancelCollection'; //取消收藏
      } else {
        url = '/api/collection/InsertCollection';
      }
      let pms = {
        CollectId: this.proId,
        Module: 5 //模块 1达人 2视频 3音乐 4话题 5商品
      };
      this.$axios
        .post(url, pms)
        .then(res => {
          if (res.data.code == 0) {
            this.isCollect = !this.isCollect;
            if (!this.isCollect) {
              this.$toast.success('已取消收藏');
            } else {
              this.$toast.success('收藏成功');
            }
          }else if(res.data.code == 1003){
            this.$toast('权限不足，请升级会员');
            this.$popVip({
              show: true,
              obj: that.$router,
              // minLeve: that.minLeve
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    getTotalData() {
      //获取数据概览数据
      let dates = this.initDateInterval(30);
      let pms = {
        proId: this.proId,
        startDate: dates[0],
        endDate: dates[1]
      };
      this.$axios({
        method: 'get',
        url: '/api/product/infodata',
        params: pms
      })
        .then(response => {
          this.loading = false;
          if (response.data.code == 0) {
            this.totalData = response.data.data;
          } else if (response.data.code == 1003) {
            this.hasRoot = false;
            // 无权限
          }
        })
        .catch(error => {
          this.loading = false;
          console.log(error);
        });
    },
    conversionRatio(val) {
      //转化率
      if (val > 1) {
        return '--';
      } else if (val < 1) {
        return this.formatRate(val, 1);
      } else {
        return '';
      }
    },
    // 图片预览（放大）
    ImgPreview(imgurl) {
      ImagePreview({
        images: [imgurl],
        closeable: true
      });
    }
  },
  filters: {
    rate(val) {
      if (!isNaN(Number(val))) {
        return (val * 100).toFixed(1) + '%';
      } else {
        return '--';
      }
    },
    setPrice(prices) {
      let maxP = (prices[0] = Number(prices[0]));
      let minP = (prices[1] = Number(prices[1]));
      if (maxP > minP) {
        return '￥' + minP + '-' + maxP;
      } else if (maxP == minP || maxP < minP) {
        return '￥' + minP;
      } else if (maxP == 0 && minP == 0) {
        return '--';
      }
    }
  },
  watch: {},
  beforeDestroy() {
    window.removeEventListener('scroll', this.setHeaderFixed); //释放window的滑动事件
  }
};
</script>

<style lang="stylus" scoped>
@import './../../common/common.styl';

.model_interval {
  padding-top: 0.01rem !important;
}

.goods_page {
  margin: 0 auto;
  font-size: rem(12);
  background-color: #f1f1f1;

  &.box_fixed {
    padding-top: rem(173);
  }

  .gp_header {
    padding: rem(30);
    background-color: #fff;

    .gp_updata_date {
      position: relative;
      text-align: center;
      height: rem(66);
      line-height: rem(66);
      background-color: #f5f5f5;
      border-radius: rem(10);
      border: solid 1px #e5e5e5;
      font-size: rem(26);
      color: #888;

      i {
        display: inline-block;
        position: absolute;
        right: rem(19);
        top: rem(19);
        width: rem(29);
        height: rem(29);
        bgp('./../../assets/img/updata.png');
      }
    }

    .gp_info {
      position: relative;
      padding-left: rem(139);
      margin-top: rem(30);
      box-sizing: border-box;
      background-color: #fff;
      transition: all linear 100ms;

      .img_box {
        position: absolute;
        left: 0;
        top: 0;
        width: rem(120);
        height: rem(120);
        border-radius: rem(20);
        background-color: #fff;
        overflow: hidden;

        img {
          width: 100%;
        }
      }

      .text_box {
        h2 {
          font-size: rem(32);
          line-height: rem(44);
          color: #222;
          margin-bottom: rem(10);
          font-weight: normal;

          &.goods_icon {
            &:before {
              content: '';
              display: inline-block;
              margin-right: rem(6);
              width: rem(28);
              height: rem(28);
              bgp('./../../assets/three/left01.png');
              margin-bottom: rem(-2);
            }
          }
        }

        .price_box {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price_text {
            p {
              font-size: rem(26);
              color: #888;
              font-family: DINPro-Medium;

              i {
                font-size: rem(24);
                color: #fd7f2c;
                font-style: normal;
              }

              .price {
                font-size: rem(36);
                margin-right: rem(14);
                color: #fd7f2c;
                // font-family: DINPro-Medium;
              }
            }
          }

          .collect_btn {
            font-size: 0;
            text-align: center;
            width: rem(140);
            height: rem(60);
            background-color: #fd7f2c;
            border: 1px solid #fd7f2c;
            border-radius: rem(10);
            border: 1px solid;
            color: #fff;
            transition: all linear 100ms;
            display: flex;
            align-items: center;
            justify-content: center;
            i {
              display: inline-block;
              width: rem(24);
              height: rem(24);
              vertical-align: middle;
              bgp('./../../assets/img/collect.png');
            }

            span {
              display: inline-block;
              font-size: rem(26);
              vertical-align: middle;
              margin-left: rem(9);
            }

            &.active {
              background-color: #fff;
              border: 1px solid #fd7f2c;
              color: #fd7f2c;

              i {
                display: none;
              }
            }
          }
        }
      }

      &.fixed {
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        margin-top: 0;
        padding: rem(30) rem(30) rem(30) rem(150);
        z-index: 19;

        // &.bt{
        // border-bottom rem(14) solid #f1f1f1
        // }
        &:after {
          content: '';
          position: absolute;
          bottom: rem(-13);
          left: 0;
          width: 100%;
          height: rem(14);
          background-color: #f1f1f1;
        }

        .img_box {
          width: rem(100);
          height: rem(100);
          top: rem(28);
          left: rem(30);
        }

        .text_box {
          .goods_icon {
            omit();
          }

          .price_box {
            .price_text {
              display: flex;
              flex-wrap: wrap;
              align-items: flex-end;
              font-size: 0;

              p {
                .price {
                  margin-right: rem(30);
                }

                &:nth-child(2) {
                  margin-left: rem(30);
                  line-height: rem(41);
                }
              }
            }

            .collect_btn {
              display: none;
            }
          }
        }
      }
    }
  }

  .gp_data {
    margin-top: rem(14);
    padding: rem(30) rem(30) rem(60);
    background-color: #fff;

    .data_box {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      .data_item {
        width: 33.33%;
        margin-top: rem(54);
        text-align: center;

        .strong {
          font-size: rem(34);
          font-family: DINPro-Medium;
          color: #222;
        }

        p {
          font-size: rem(24);
          margin-top: rem(10);
          color: #888;
        }
      }
    }
  }
}

.goods_main {
  margin-top: rem(14);
  background-color: #fff;

  .van-tabs {
    .van-tabs__wrap {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
    }
  }
}

.loading_box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: rem(281);
}

.nodata_page {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .img_box {
    width: rem(297);
    height: rem(232);

    img {
      width: 100%;
      height: 100%;
    }
  }

  p {
    font-size: rem(26);
    color: #888;
  }
}
</style>
